<?php

namespace app\liantang\service;

use think\admin\Service;
use think\Cache;
use think\admin\service\QueueService;

/**
 * 表单数据接口服务
 * Class UserService
 * @package app\store\service
 */
class FormService extends Service
{
    

    /**
     * 更新用户用户参数
     * @param int $template_id 表单模板ID
     * @param array $fields 字段数据
     * @param int $area_id 警区ID
     * @param string $location 经纬度
     * @param string $uuid 用户ID
     * @return boolean
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save($collect_id, $template_id, $fields)
    {

        $template = $this->app->db->name("DigitTemplate")->where(["id" => $template_id])->find();

        // {Y}：代表年
        // {M}：代表月
        // {D}：代表日
        // {U}：代表用户姓名
        // {T}：代表模板名称
        // {字段名}：该字段填写的内容

        $title = str_replace("{Y}", date("Y"), $template["auto_title"]);
        $title = str_replace("{M}", date("m"), $title);
        $title = str_replace("{D}", date("d"), $title);

        $title = str_replace("{H}", date("H"), $title);
        $title = str_replace("{I}", date("i"), $title);
        $title = str_replace("{S}", date("s"), $title);

        $title = str_replace("{T}", $template["name"], $title);

        // 替换字段
        foreach ($fields as $field) {
            if (strpos($title, "{".$field["name"]."}") !== false){
                !empty($field["value"]) && $title = str_replace("{".$field["name"]."}", $field["value"], $title);
            }
        }

        $ids = $this->_buildRecord($fields); // 字段编辑

        $collect_data = array(
            "title" => $title,
            "digit_template_code" => $template["code"],
            "create_by" => $uuid,
            "digit_collect_record_ids" => $ids
        );

        if ($collect_id == 0) {
            $collect_id = $this->app->db->name("DigitCollect")->insertGetId($collect_data);
        } else {
            $collect_data["id"] = $collect_id;
            data_save("DigitCollect", $collect_data, 'id');
        }

        return $collect_id;

    }


    /**
     * 字段更新操作
     * @param array $data
     * @param array $ids
     * @return string
     * @throws \think\db\exception\DbException
     */
    private function _buildRecord(array $fields, array $ids = []): string
    {   

        foreach ($fields as $vo) {

            $collect_record = array(
                "digit_template_field_id" => $vo['digit_template_field_id'],
                "digit_template_field_name" => $vo['name'],
                "digit_template_field_type" => $vo['type'],
                "content" => isset($vo['value']) ? $vo['value'] : "",
                "digit_template_field_setting" => json_encode($vo['setting']),
            );

            if (empty($vo['id'])) {

                $result = $id = $this->app->db->name('DigitCollectRecord')->insertGetId($collect_record);

            } else {

                $id = intval($vo['id']);

                $result = $this->app->db->name('DigitCollectRecord')->where('id', $id)->update($collect_record);

            }



            if ($result !== false) array_push($ids, $id);

        }

        return join(',', $ids);

    }




    /**
     * [populate description]
     * @param  array $list 上报记录列表
     * @return [type]       [description]
     */
    function populates($list){

        return $list;
    }


}